package com.my.study.algorithm.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 树的层级遍历
 * 
 * 
 * @author Carlos
 * @version 1.0.0
 * @date 2023/3/7 22:00
 */
public class TreeLevelErgodic {
    
    private static List<List<Integer>> twoListErgodic(TreeNode root) {
        if (null == root) {
            return new ArrayList<>();
        }
        List<List<Integer>> ans = new ArrayList<>();
        List<TreeNode> curList = new ArrayList<>();
        curList.add(root);
        
        while (!curList.isEmpty()) {
            List<TreeNode> next = new ArrayList<>();
            List<Integer> valList = new ArrayList<>(curList.size());

            for (TreeNode node : curList) {
                if (node.left != null) {
                    next.add(node.left);
                }
                if (node.right != null) {
                    next.add(node.right);
                }
                valList.add(node.val);
            }
            curList = next;
            ans.add(valList);
        }
        
        return ans;
    }
    
    
    private static List<List<Integer>> queueListErgodic(TreeNode root) {
        if (null == root) {
            return new ArrayList<>();
        }
        List<List<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> cur = new ArrayDeque<>();
        cur.add(root);
        
        while (!cur.isEmpty()) {
            int size = cur.size();
            List<Integer> vals = new ArrayList<>(size);
            while (size-- > 0) {
                TreeNode node = cur.poll();
                vals.add(node.val);
                if (node.left != null) {
                    cur.add(node.left);
                }
                if (node.right != null) {
                    cur.add(node.right);
                }
            }
            ans.add(vals);
        }
        
        return ans;
    }
    
}



class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}